// 函数组件
import React, { useState, useEffect, useContext, useRef } from 'react';
import "./css/Freight.less"
import { Table, Modal, message, ConfigProvider, Form, InputNumber, Button } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import FreightDialog from './child/FreightDialog';
import zh_CN from 'antd/es/locale/zh_CN';
import { delFreight, setMoney, showFreight, showMoney } from '../../../api/operationApi';

interface DataType {
    freightId: number,
    freightArea: string,
    freightAmount: number,
}

// 表单布局
const layout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 16,
    },
};
// 表单验证
const validateMessages = {
    required: '${label}必填',
    types: {
        number: '${label}必须是数值',
    }
};


function OperationFreight() {
    const [form] = Form.useForm();

    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'freightId',
            align: 'center',
            width: '15%'
        },
        {
            title: '地区',
            dataIndex: 'freightArea',
            align: 'center',
        },
        {
            title: '运费',
            dataIndex: 'freightAmount',
            align: 'center',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            render: (value, record) => (
                <div>
                    <button className='edit' onClick={() => clickMod(record)}>编辑</button>
                    <button className='del' onClick={() => clickDel(record)}>删除</button>
                </div>
            ),
        },
    ];

    const [currentPage, setCurrentPage] = useState<number>(1) // 当前页
    const [pageSize, setPageSize] = useState<number>(10)  // 一页条数
    const [count, setCount] = useState<number>() // 总数


    // 表格数据
    const [data, setData] = useState<DataType[]>([])

    // 1、表格渲染数据
    useEffect(() => {
        getData(currentPage, pageSize)
    }, [currentPage, pageSize])

    // 1-1 删除当前页最后一项，页码改变
    useEffect(() => {
        if (currentPage > 1 && data.length === 0) {
            setCurrentPage(currentPage - 1)
        }
    }, [data])

    // 1-2 获取数据
    async function getData(currentPage: number, pageSize: number) {
        let res = await showFreight(
            {
                "currentPage": currentPage,
                "pageSize": pageSize
            }
        )
        console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'res', res);
        setCount(res.data.total)
        setData(res.data.freights)
    }

    // 1-3 改变页码
    const getPageContent = (currentPage: number, pageSize: number) => {
        setCurrentPage(currentPage)
        setPageSize(pageSize)
    }

    // 2、删除
    const { confirm } = Modal;
    const clickDel = (item: DataType) => {
        confirm({
            title: '确定删除该地区运费吗?',
            icon: <ExclamationCircleFilled />,
            content: '删除之后就没了哦~',
            async onOk() {
                await delFreight({
                    id: item.freightId
                })
                getData(currentPage, pageSize)
                message.success('删除成功')
            },
            onCancel() {
                message.warning('取消操作')
            },
        });
    }

    // 3、设置金额弹框部分
    const [freight, setFreight] = useState<number>()
    const [isSetOpen, setIsSetOpen] = useState<boolean>(false)
    useEffect(()=>{
        async function getMoney(){
            let res = await showMoney()
            console.log('res',res);
            setFreight(res.data)
        }
        getMoney()
    },[])

    const clickSet = () => {
        form.resetFields()
        setIsSetOpen(true)
    }

    const onFinish = async (values: any) => {
        console.log("values", values);
        let res = await setMoney({
            money:values.freightAmount
        })
        setFreight(values.freightAmount)
        message.success('设置成功')
        setIsSetOpen(false)   
    };




    //  4、点击添加，弹出弹框
    const [type, setType] = useState<string>('')
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false); // 对话框是否打开
    const clickAdd = () => {
        setType("add")
        setIsModalOpen(true)
    }


    // 点击修改，传递值
    const [modStuInfo, setModStuInfo] = useState<DataType>()
    const clickMod = (item: DataType): void => {
        setType('mod')
        setModStuInfo(item)
        // 弹框显示
        setIsModalOpen(true)
    }

    // 点击取消
    const close = () => {
        setIsModalOpen(false)
    }

    
    return (
        <div className='OperationFreight'>
            {/* 头部 */}
            <div className='page-top'>
                {/*左边标题  */}
                <div className='page-title'>
                    <p>运费管理</p>
                </div>
            </div>

            {/* 内容区 */}
            <div className='page-context'>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='list-title'>
                        <p>包邮设置</p>
                        <div className='list-operation'>
                            <div>
                                <p>包邮金额：{freight}</p>
                                <p onClick={clickSet}>设置</p>
                            </div>
                            <div>
                                <button className='add' onClick={clickAdd}>添加</button>
                            </div>
                        </div>
                    </div>

                    {/* 表格部分 */}
                    <ConfigProvider locale={zh_CN}>
                        <Table
                            className='table'
                            columns={columns}
                            dataSource={data}
                            scroll={{ y: 444 }}
                            rowKey={item => item.freightId}
                            pagination={{
                                position: ['bottomCenter'],
                                total: count,
                                pageSize: pageSize,
                                onChange: getPageContent,
                                defaultPageSize: 10,
                                pageSizeOptions: [3, 5, 10, 15],
                                showQuickJumper: true,
                                showSizeChanger: true,
                            }}
                        />
                    </ConfigProvider>


                </div>

            </div>

            {/* 弹框 */}
            <FreightDialog data={data} currentPage={currentPage} pageSize={pageSize} getData={getData}  isModalOpen={isModalOpen} modStuInfo={modStuInfo} type={type} close={close}></FreightDialog>


            <Modal centered={true} forceRender width={460} title='设置金额' open={isSetOpen} footer={null} onCancel={() => setIsSetOpen(false)} >
                <Form
                    {...layout}
                    name="freight-form"
                    onFinish={onFinish}
                    validateMessages={validateMessages}
                    form={form}
                >
                    <Form.Item
                        name='freightAmount'
                        label="设置金额"
                        initialValue={freight}
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <InputNumber />
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            ...layout.wrapperCol,
                            offset: 8,
                        }}
                    >
                        <Button type="primary" htmlType="submit" className='confirm-btn' >确定</Button>
                        <Button type="primary" onClick={() => setIsSetOpen(false)} ghost>取消</Button>
                    </Form.Item>
                </Form>
            </Modal>


        </div >
    )
}

export default OperationFreight